package screen;


import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordStore;

public class JXBMCConfigure extends Form {

    private TextField webAddressItem;
    private TextField screenWidth;
    private TextField screenHeight;
    private RecordStore rs = null;
    static final String WEB_ADDRESS = "webAddress";
    static final String SCREEN_WIDTH = "screenWidth";
    static final String SCREEN_HEIGHT = "screenHeight";

    public JXBMCConfigure() {
        super("Configure");
        webAddressItem = new TextField("Xbmc IpAddress", "", 20, TextField.ANY);
        this.append(webAddressItem);

        screenWidth = new TextField("Screen Width", "", 20, TextField.ANY);
        this.append(screenWidth);

        screenHeight = new TextField("Screen Height", "", 20, TextField.ANY);
        this.append(screenHeight);

        init();
    }

    public String getProperty(String propertyName, String defaultVal) {
        String propertyVal = defaultVal;
        try {
            rs = RecordStore.openRecordStore(propertyName, true);
            if (rs.getNumRecords() > 0) {
                byte[] recData = new byte[5];
                int len;
                if (rs.getRecordSize(1) > recData.length) {
                    recData = new byte[rs.getRecordSize(1)];
                }
                len = rs.getRecord(1, recData, 0);
                propertyVal = new String(recData, 0, len);
            }
            rs.closeRecordStore();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propertyVal;
    }

    public void setProperty(String propertyName, String propertyVal) {
        try {
            rs.deleteRecordStore(propertyName);
            rs = RecordStore.openRecordStore(propertyName, true);

            byte[] value = propertyVal.getBytes();
            rs.addRecord(value, 0, value.length);

            rs.closeRecordStore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init() {
        String webAddressString = this.getProperty(WEB_ADDRESS, "127.0.0.1");
        webAddressItem.setString(webAddressString);

        String screenHeightString = this.getProperty(SCREEN_HEIGHT, "320");
        screenHeight.setString(screenHeightString);

        String screenWidthString = this.getProperty(SCREEN_WIDTH, "240");
        screenWidth.setString(screenWidthString);
    }

    public void store() {
        

        this.setProperty(WEB_ADDRESS, webAddressItem.getString());
        this.setProperty(SCREEN_HEIGHT, screenHeight.getString());
        this.setProperty(SCREEN_WIDTH, screenWidth.getString());
    }

    public String getWebAddress() {
        return webAddressItem.getString();
    }

    public String getScreenWidth() {
        return screenWidth.getString();
    }

    public String getScreenHeight() {
        return screenHeight.getString();
    }
}
